import { Player } from "@minecraft/server";
import { ModalFormData } from "@minecraft/server-ui";
import { Dimensions } from "@sapi-game/constants";
import { Game, GameComponent } from "@sapi-game/main";
import { DimensionIds } from "@sapi-game/utils/vanila-data";
import { PKConfigManager } from "@/parkour/config";
import { PKMaps } from "@/parkour/maps";
import { isAdmin } from "sapi-pro/scripts/func";
import { PKPreParingState } from "../state";

export class PKConfigSetter extends GameComponent<PKPreParingState> {
    floatTextLoc = { x: 727.5, y: -58, z: 439.5 };

    override onAttach(): void {
        this.updateFloatText();
        this.subscribe(
            Game.events.buttonPush,
            (t) => {
                if (t.source instanceof Player) {
                    if (!isAdmin(t.source)) {
                        t.source.sendMessage("你不是管理员，无权操作");
                        return;
                    }
                    this.showConfigForm(t.source);
                }
            },
            {
                loc: [726, -59, 439],
                dimensionId: DimensionIds.Overworld,
            }
        );
    }

    showConfigForm(player: Player) {
        const config = PKConfigManager.get();

        const form = new ModalFormData()
            .title("你的跑酷我来造配置")
            .dropdown(
                "地图",
                Object.values(PKMaps).map((m) => m.name),
                { defaultValueIndex: config.mapIndex }
            )
            .textField("建造时间", "请输入建造时间", {
                defaultValue: config.buildTime.toString(),
            })
            .textField("跑酷时间", "请输入建造时间", {
                defaultValue: config.runTime.toString(),
            })
            .textField("生命数", "请输入最大尝试次数", {
                defaultValue: config.lives.toString(),
            });
        form.show(player).then((res) => {
            if (!res.formValues) return;
            const map = res.formValues[0] as number;
            const buildTime = parseInt(res.formValues[1] as string);
            const runTime = parseInt(res.formValues[2] as string);
            const lives = parseInt(res.formValues[3] as string);
            PKConfigManager.set({
                mapIndex: map,
                buildTime: buildTime,
                lives: lives,
                runTime: runTime,
            });
            this.updateFloatText();
        });
    }

    updateFloatText() {
        const dim = Dimensions.Overworld;
        const entites = dim.getEntities({
            location: this.floatTextLoc,
            maxDistance: 2,
            type: "game:floattext",
        });
        if (entites.length > 1) {
            entites.forEach((e, idx) => {
                if (idx != 0) e.remove();
            });
        }
        const entity =
            entites[0] ?? dim.spawnEntity("game:floattext", this.floatTextLoc);

        entity.nameTag = this.buildName();
    }

    buildName(): string {
        const config = PKConfigManager.get();
        const maps = Object.values(PKMaps);
        const map = maps[config.mapIndex] ?? maps[0];
        const lines = [
            `§g§l 你的跑酷我来造 v1.0 `,
            "§7-----------------§r",
            `§3| 地图: ${map.name} |`,
            `§a| 建造时间: ${config.buildTime} 秒 |`,
            `§d| 跑酷时间: ${config.runTime} 秒 |`,
            `§c| 生命数: ${config.lives} |`,
            "§7-----------------§r",
        ];
        return lines.join("\n");
    }
}
